/**
 * 
 */
package com.activities;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.Adapters.PostAdapter;
import com.Adapters.Items.ItemPost;
import com.Adapters.Items.ItemPostPicture;
import com.Adapters.Items.RowType;
import com.Animations.AnimUtil;
import com.Animations.AnimationLists;
import com.Data.Albums;
import com.Data.Albums.onDeleteCompleted;
import com.Data.Albums.onUpdateCompleted;
import com.Data.Post;
import com.Data.Post.OnGetPicturesCompleted;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureIntentManagerClass;
import com.Managers.ThemeManager;
import com.Managers.UserManagerClass;
import com.PopUps.PopUpClass;
import com.SoapClasses.SoapUtil;
import com.TextFormat.UtilFonts;
import com.UtilDate.UtilDate;
import com.gallery.ActivityGallery;
import com.shareup.R;


/**
 * @author Chris
 * 
 */
public class ActivityAlbumDetail extends Activity implements DefaultFunctions {

    public static Albums album;

    private PostAdapter adapter;

    private ListView listview;

    private ViewGroup table;

    private FrameLayout messageLoading;

    private View backB;

    private View infoB;

    private RelativeLayout mActionbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ThemeManager.setTheme(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album_detail);
        Init();

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#clear()
     */
    @Override
    public void clear() {

        if (adapter != null) {
            adapter.clear();
            adapter.notifyDataSetChanged();
        }

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#contains(int)
     */
    @Override
    public boolean contains(int object) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (p.getPostId() == object)
                return true;

        }

        return false;
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#getParentActivity()
     */
    @Override
    public Activity getParentActivity() {

        return this;
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#Init()
     */
    @Override
    public void Init() {

        mActionbar = (RelativeLayout) findViewById(R.id.layout_include);
        TextView title = (TextView) findViewById(R.id.title_actionbar);
        UtilFonts.setTextBoldFont(title);

        title.setText(album.getName());
        infoB = findViewById(R.id.button_info);
        backB = findViewById(R.id.button_back);
        backB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                exit();
            }
        });
        infoB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                showInfoActivity();
            }
        });
        listview = (ListView) findViewById(R.id.grid_main);
        adapter = new PostAdapter(this, this, R.layout.item_post_picture);
        listview.setAdapter(adapter);
        listview.setOnScrollListener(adapter);
        messageLoading = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.item_loading, null);
        table = (TableRow) findViewById(R.id.aExplore_table_tooltip);

        loadFrom(SoapUtil.MODE_ALBUM, 0);

    }

    private void showInfoActivity() {

        SoapUtil.ALBUM_NAME = album.getName();

        SoapUtil.ALBUM_ID = album.getID();

        PictureIntentManagerClass.createChooserImage(this);

        Intent intent = new Intent(this, ActivityGallery.class);
        // startActivity(intent);

    }

    private void exit() {

        finish();
        AnimUtil.getActivityTransition(this, false);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == PictureIntentManagerClass.START_UPLOADING) {
            if (resultCode == RESULT_OK) {
                FragmentManagerClass.RefreshPictureList();
            }
        }
        else
            if (requestCode == ActivityUpload.SELECT_PHOTO) {
                if (resultCode == RESULT_OK) {
                    PictureIntentManagerClass.startIntentForCrop(false, data, this);
                }
            }
            else
                if (requestCode == ActivityUpload.CROP_PIC) {
                    if (resultCode == RESULT_OK) {
                        Intent intent = new Intent(this, ActivityUpload.class);
                        startActivityForResult(intent, PictureIntentManagerClass.START_UPLOADING);
                        AnimUtil.getActivityTransition(this, true);
                    }
                }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            //
            return true;
        }
        //
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {

        FragmentManagerClass.aAlbumDetail = null;
        album = null;

        AnimationLists.displayedImages.clear();
        AnimationLists.displayedThumbs.clear();

        super.onDestroy();
    }

    @Override
    protected void onResume() {

        FragmentManagerClass.aAlbumDetail = this;

        super.onResume();
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#loadFrom(int)
     */
    @Override
    public void loadFrom(int SoapUtilMode, int index) {

        if (adapter == null) {
            Init();

        }
        Post getPic = new Post(adapter.getCount(), 0, this, SoapUtilMode, "", new OnGetPicturesCompleted() {

            @Override
            public void Completed(Post[] result) {

                resultList(result);

            }
        });
        setLoading();
        delayTask(getPic);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#loadFromTags(java.lang.String)
     */
    @Override
    public void loadFromTags(String tag) {

        Post getPic = new Post(adapter.getCount(), 0, this, SoapUtil.MODE_TAGS, tag, new OnGetPicturesCompleted() {

            @Override
            public void Completed(Post[] result) {

                resultList(result);

            }
        });
        setLoading();
        delayTask(getPic);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#onConnection()
     */
    @Override
    public void onConnection() {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#onNoConnection()
     */
    @Override
    public void onNoConnection() {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#refresh()
     */
    @Override
    public void refresh() {

        this.loadFrom(SoapUtil.MENU_VIEW, 0);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#remove(java.lang.Object)
     */
    @Override
    public void remove(Object object) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (((Post) object).getID() == p.getPostId()) {
                adapter.remove(((Post) object));
                adapter.notifyDataSetChanged();
            }
        }
        if (adapter.getCount() == 0) {
            setNoItemsMessage();
            album.setCover("0");
            updateAlbum();

        }

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#remove(java.lang.Object,
     * com.Data.Albums.onDeleteCompleted)
     */
    @Override
    public void remove(Object object, onDeleteCompleted callback) {

        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#resultList(java.lang.Object[])
     */
    @Override
    public void resultList(Object[] result) {

        boolean changes = false;
        for (Post p : (Post[]) result) {
            if (!contains(p.getID())) {
                adapter.add(p);
                changes = true;
            }

        }
        if (changes)
            adapter.notifyDataSetChanged();

        this.stopLoading();

        if (adapter.getCount() == 0) {
            setNoItemsMessage();
            album.setCover("0");
            FragmentManagerClass.aAlbum.setAlbum(album);

        }

    }

    private void updateAlbum() {

        Albums send = new Albums(Albums.ACTION_UPDATE);
        send.setContext(this);
        send.setCallbackUpdate(new onUpdateCompleted() {

            @Override
            public void Completed(String result) {

                updateAlbum(album);

            }
        });

        send.setID(album.getID());
        send.setOwner(album.getOwner());
        send.setPin(album.getPin());
        send.setPrivacy(album.getPrivacy());
        send.setName(album.getName());
        send.setCover(album.getCover());

        send.execute();

    }

    private void updateAlbum(Albums album) {

        FragmentManagerClass.aAlbum.setAlbum(album);
        exit();
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#setLoading()
     */
    @Override
    public void setLoading() {

        if (table.getChildCount() != 0) {
            table.removeAllViews();
        }
        table.addView(messageLoading);
        AnimUtil.animatePopUp(table, true, null);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#setMessage(java.lang.String, int)
     */
    @Override
    public void setMessage(String message, int iconResource) {

        new PopUpClass(this).setMessage(message, iconResource, table);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#setNoItemsMessage()
     */
    @Override
    public void setNoItemsMessage() {

        String message = "";
        int icon = 0;

        icon = R.drawable.album_pressed;
        message = getString(R.string.dialog_no_albums_explore);

        this.setMessage(message, icon);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#stopLoading()
     */
    @Override
    public void stopLoading() {

        AnimUtil.animatePopUp(table, false, null);

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updateComments(int, int)
     */
    @Override
    public void updateComments(int idPicture, int count) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (p.getPostId() == idPicture)
                p.setCommentsCount(count);

        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void updateLikes(int idPicture, int count) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            if (p.getPostId() == idPicture)
                p.setLikesCount(count);

        }
        adapter.notifyDataSetChanged();
    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updatePermissions(int, int)
     */
    @Override
    public void updatePermissions(int id, int newPermissions) {

        for (int i = 0; i < adapter.getCount(); i++) {
            ItemPost p = adapter.getPost(i);
            // IF ITS TYPE PICTURE
            if (p.getViewType() == RowType.PICTURE_POST.ordinal()) {
                ItemPostPicture pic = ((ItemPostPicture) p);
                if (pic.getPicture().getUser().getID() != UserManagerClass.UserLogged.getID()) {
                    if (id == pic.getPicture().getUser().getID()) {
                        pic.getPicture().setPermission(newPermissions);
                        pic.setOwnerShip();

                    }
                }
                else
                    break;

            }
        }

    }

    /*
     * (non-Javadoc)
     * @see com.activities.DefaultFunctions#updateTime(int)
     */
    @Override
    public void updateTime(int id) {

        for (int i = 0; i < adapter.getCount(); i++) {

            ItemPost p = adapter.getPost(i);

            if (id == p.getPostId()) {
                View v = listview.getChildAt(i);
                TextView date = (TextView) v.findViewById(R.id.user_date);
                UtilDate dt = new UtilDate(v.getContext());
                dt.setTimeDifference(p.getPublicationDate(), date);
            }
        }

    }

    private void delayTask(final Post pictures) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                pictures.execute();
            }
            //
        }, 1000);
    }

}
